package com.own.business.level.business.core.impl;

import com.own.business.level.business.core.ExpRuleFunction;
import com.own.business.level.business.model.ExpModel;
import com.own.business.level.business.service.LevelUserHistoryService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * LoginExpRuleFunction
 *
 * @author chenxueli
 * @date 2022-08-17 17:01:00
 */
@Component
public class LoginExpRuleFunction implements ExpRuleFunction {

    private static final Map<Integer, Integer> EXP_CONTINUE_MAP = new HashMap<>();
    private static final Integer CONTINUE_DEFAULT = 5;

    static {
        EXP_CONTINUE_MAP.put(0, 1);
        EXP_CONTINUE_MAP.put(1, 2);
        EXP_CONTINUE_MAP.put(2, 2);
        EXP_CONTINUE_MAP.put(3, 3);
        EXP_CONTINUE_MAP.put(4, 3);
        EXP_CONTINUE_MAP.put(5, 3);
        EXP_CONTINUE_MAP.put(6, 4);
        EXP_CONTINUE_MAP.put(7, CONTINUE_DEFAULT);
    }

    @Resource
    private LevelUserHistoryService levelUserHistoryService;

    /**
     * 当前次增加数量（如果数量为0，则不能添加）
     *
     * @param userId 登录的用户id
     * @return 当前次提升的数量
     */
    @Override
    public ExpModel increase(Long userId) {
        // 如果当天没有获取过登录经验，则可以继续获取
        var history = levelUserHistoryService.last(userId, type());
        // 如果今天已经添加过了，则不能再次添加了
        var flag = history == null || !history.getOperateDate().equals(LocalDate.now());
        if (!flag) {
            return ExpModel.ZERO;
        }
        if (history == null || !history.getOperateDate().equals(LocalDate.now().minusDays(1))) {
            return ExpModel.builder().exp(1).type(type()).message("登录奖励").build();
        }
        // 判断连续登录了多少天
        return ExpModel.builder()
                .exp(EXP_CONTINUE_MAP.getOrDefault(history.getConsecutive(), CONTINUE_DEFAULT))
                .count(history.getConsecutive())
                .type(type())
                .message(String.format("连续登录%d天", history.getConsecutive() + 1))
                .build();
    }

    @Override
    public String type() {
        return "login";
    }

}
